import { FC, useEffect, useState, useCallback } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Space,
  message,
  Upload,
} from 'antd';
import {
  SaveOutlined,
  RollbackOutlined,
  UploadOutlined,
  MinusCircleOutlined,
  PlusOutlined,
  LeftOutlined,
} from '@ant-design/icons';
import { useParams, useNavigate } from 'react-router-dom';
import debounce from 'lodash/debounce';
import type { UploadProps } from 'antd';
import { reportApi } from 'services/report';
import {
  ReportAttachment,
  ReportDetail,
  ReportFormData,
  ReportStatus,
  ReportType,
} from 'types/report';

import MainLayout from '../../../components/MainLayout';
import RichTextEditor from '../components/RichTextEditor';
import AttachmentList from '../components/AttachmentList';

import styles from './index.module.css';

const { Option } = Select;

// 文件上传配置
const UPLOAD_CONFIG = {
  maxSize: 50 * 1024 * 1024, // 50MB
  acceptTypes: ['.doc', '.docx', '.pdf', '.xls', '.xlsx', '.jpg', '.png'],
  maxCount: 10,
};

const ReportEdit: FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();

  const [form] = Form.useForm<ReportFormData>();
  const [loading, setLoading] = useState(false);
  const [attachments, setAttachments] = useState<ReportAttachment[]>([]);
  const [autoSaveTime, setAutoSaveTime] = useState<string>('');

  const isEdit = !!id;

  const fetchReportDetail = useCallback(async () => {
    if (!id) return;
    setLoading(true);
    try {
      const res = await reportApi.getReportDetail(id);
      if (res.code === 200) {
        const report = res.data;

        form.setFieldsValue({
          title: report.title,
          type: report.type as ReportType,
          // content: report.content.sections
          //   .map((section) => section.content)
          //   .join('\n'),
          content: report.content,
          // conclusion: report.content?.conclusion || '',
          author: report.author,
          status: report.status as ReportStatus,
          tags: report.tags,
          summary: report.summary,
          version: report.version,
          references: report.references,
        });

        // 设置附件列表
        if (report.attachments) {
          setAttachments(report.attachments);
        }
      }
    } catch (error) {
      console.error('获取报告详情失败:', error);
      message.error('获取报告详情失败');
    } finally {
      setLoading(false);
    }
  }, [id, form]);

  useEffect(() => {
    if (isEdit) {
      fetchReportDetail();
    } else {
      // 新建报告时设置默认值
      form.setFieldsValue({
        status: 'draft',
        type: 'industry',
        author: '系统管理员',
      });
    }
  }, [form, isEdit, fetchReportDetail]);

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      // 构建提交数据
      const submitData = {
        ...values,
        content: {
          sections: [
            {
              title: '正文',
              content: values.content,
            },
          ],
          conclusion: values.conclusion || '',
        },
        attachments,
      };

      let res;
      if (isEdit) {
        // res = await reportApi.updateReport(id!, submitData);
      } else {
        // res = await reportApi.createReport(submitData);
      }

      // if (res.code === 200) {
      //   message.success(`${isEdit ? '更新' : '创建'}成功`);
      //   navigate('/report');
      // }
    } catch (error) {
      console.error('提交失败:', error);
      message.error(`${isEdit ? '更新' : '创建'}失败`);
    } finally {
      setLoading(false);
    }
  };

  // 自动保存函数
  const autoSave = useCallback(
    debounce(async (values: ReportFormData) => {
      if (!id) return; // 只在编辑模式下自动保存

      try {
        const submitData: Partial<ReportDetail> = {
          ...values,
          content: values.content,
          // content: {
          //   sections: [
          //     {
          //       title: '正文',
          //       content: values.content,
          //     },
          //   ],
          //   conclusion: '',
          // },
        };

        await reportApi.updateReport(id, submitData);
        setAutoSaveTime(new Date().toLocaleTimeString());
      } catch (error) {
        console.error('自动保存失败:', error);
      }
    }, 2000),
    [id]
  );

  // 监听表单变化
  const handleFormChange = () => {
    const values = form.getFieldsValue();
    autoSave(values);
  };

  // 文件上传前的校验
  const beforeUpload = (file: File) => {
    // 检查文件类型
    const isValidType = UPLOAD_CONFIG.acceptTypes.some((type) =>
      file.name.toLowerCase().endsWith(type)
    );
    if (!isValidType) {
      message.error('不支持的文件类型！');
      return Upload.LIST_IGNORE;
    }

    // 检查文件大小
    if (file.size > UPLOAD_CONFIG.maxSize) {
      message.error(
        `��件大小不能超过 ${UPLOAD_CONFIG.maxSize / 1024 / 1024}MB！`
      );
      return Upload.LIST_IGNORE;
    }

    // 检查文件数量
    if (attachments.length >= UPLOAD_CONFIG.maxCount) {
      message.error(`最多只能上传 ${UPLOAD_CONFIG.maxCount} 个文件！`);
      return Upload.LIST_IGNORE;
    }

    return true;
  };

  const uploadProps: UploadProps = {
    name: 'file',
    action: '/api/upload',
    headers: {
      authorization: 'authorization-text',
    },
    accept: UPLOAD_CONFIG.acceptTypes.join(','),
    beforeUpload,
    onChange(info) {
      if (info.file.status === 'done') {
        const response = info.file.response;
        if (response?.code === 200) {
          const newAttachment: ReportAttachment = {
            fileId: response.data.fileId,
            fileName: info.file.name,
            fileSize: info.file.size || 0,
            fileType: info.file.name.split('.').pop() || '',
            url: response.data.url,
          };
          setAttachments((prev) => [...prev, newAttachment]);
          message.success(`${info.file.name} 上传成功`);
        }
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
    },
  };

  const handlePreview = (file: ReportAttachment) => {
    window.open(file.url);
  };

  const handleDelete = (file: ReportAttachment) => {
    setAttachments((prev) =>
      prev.filter((item) => item.fileId !== file.fileId)
    );
    message.success('删除成功');
  };

  return (
    <MainLayout>
      <Card
        title={
          <Space>
            <LeftOutlined
              className={styles.backIcon}
              onClick={() => navigate('/report')}
            />
            {isEdit ? '编辑报告' : '新建报告'}
          </Space>
        }
        extra={
          <Space>
            <Upload {...uploadProps}>
              <Button icon={<UploadOutlined />}>上传附件</Button>
            </Upload>
            <Button
              icon={<RollbackOutlined />}
              onClick={() => navigate('/report')}
            >
              返回
            </Button>
            <Button
              type="primary"
              icon={<SaveOutlined />}
              onClick={handleSubmit}
            >
              保存
            </Button>
          </Space>
        }
      >
        <Form form={form} layout="vertical" onValuesChange={handleFormChange}>
          <Form.Item
            name="title"
            label="报告标题"
            rules={[{ required: true, message: '请输入报告标题' }]}
          >
            <Input placeholder="请输入报告标题" />
          </Form.Item>

          <Form.Item
            name="type"
            label="报告类型"
            rules={[{ required: true, message: '请选择报告类型' }]}
          >
            <Select>
              <Option value="industry">产业报告</Option>
              <Option value="phase">阶段报告</Option>
              <Option value="custom">定制报告</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="author"
            label="作者"
            rules={[{ required: true, message: '请输入作者' }]}
          >
            <Input placeholder="请输入作者" />
          </Form.Item>

          <Form.Item
            name="summary"
            label="报告摘要"
            rules={[{ required: true, message: '请输入报告摘要' }]}
          >
            <Input.TextArea rows={4} placeholder="请输入报告摘要" />
          </Form.Item>

          <Form.Item
            name="content"
            label="报告内容"
            rules={[{ required: true, message: '请输入报告内容' }]}
          >
            <RichTextEditor />
          </Form.Item>

          <Form.Item name="conclusion" label="结论">
            <Input.TextArea rows={4} placeholder="请输入报告结论" />
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select>
              <Option value="draft">草稿</Option>
              <Option value="published">发布</Option>
              <Option value="archived">归档</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="version"
            label="版本"
            rules={[{ required: true, message: '请输入版本号' }]}
          >
            <Input placeholder="请输入版本号" />
          </Form.Item>

          <Form.Item name="tags" label="标签">
            <Select
              mode="tags"
              style={{ width: '100%' }}
              placeholder="请输入标签"
              tokenSeparators={[',']}
            />
          </Form.Item>

          <Form.Item
            label={
              <Space>
                附件
                <div className={styles.uploadHint}>
                  支持格式：{UPLOAD_CONFIG.acceptTypes.join('、')}；
                  单个文件大小不超过 {UPLOAD_CONFIG.maxSize / 1024 / 1024}MB；
                  最多上传 {UPLOAD_CONFIG.maxCount} 个文件
                </div>
              </Space>
            }
          >
            <Space direction="vertical" style={{ width: '100%' }}>
              <Upload {...uploadProps}>
                <Button icon={<UploadOutlined />}>上传附件</Button>
              </Upload>
              <AttachmentList
                attachments={attachments}
                onPreview={handlePreview}
                onDelete={handleDelete}
              />
            </Space>
          </Form.Item>

          <Form.Item name="references" label="参考资料">
            <Form.List name="references">
              {(fields, { add, remove }) => (
                <>
                  {fields.map(({ key, name, ...restField }) => (
                    <Space
                      key={key}
                      style={{ display: 'flex', marginBottom: 8 }}
                      align="baseline"
                    >
                      <Form.Item
                        {...restField}
                        name={[name, 'title']}
                        rules={[{ required: true, message: '请输入标题' }]}
                      >
                        <Input placeholder="标题" style={{ width: 300 }} />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        name={[name, 'url']}
                        rules={[{ required: true, message: '请输入链接' }]}
                      >
                        <Input placeholder="链接" style={{ width: 400 }} />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        name={[name, 'type']}
                        rules={[{ required: true, message: '请选择类型' }]}
                      >
                        <Select style={{ width: 120 }}>
                          <Option value="web">网页</Option>
                          <Option value="book">书籍</Option>
                          <Option value="paper">论文</Option>
                        </Select>
                      </Form.Item>
                      <MinusCircleOutlined onClick={() => remove(name)} />
                    </Space>
                  ))}
                  <Form.Item>
                    <Button
                      type="dashed"
                      onClick={() => add()}
                      block
                      icon={<PlusOutlined />}
                    >
                      添加参考资料
                    </Button>
                  </Form.Item>
                </>
              )}
            </Form.List>
          </Form.Item>

          {autoSaveTime && (
            <div className={styles.autoSaveHint}>
              上次自动保存时间：{autoSaveTime}
            </div>
          )}
        </Form>
      </Card>
    </MainLayout>
  );
};

export default ReportEdit;
